import type { MenuProps } from "antd";
import { Button, Divider, Menu, message, Modal, Popover, Progress } from "antd";
import { useEffect, useMemo, useState } from "react";
import { Route, Routes, useLocation, useNavigate } from "react-router";
import { DocGeneration } from "./pages/DocGeneration";
import { LegalAdvice } from "./pages/LegalAdvice";
import { LegalSearch } from "./pages/LegalSearch";
import { TextRead } from "./pages/TextRead";
import { CaseDetail } from "./pages/CaseDetail";
import { LawDetail } from "./pages/LawDetail";
import {
  useAppStore,
  useDocGenerationStore,
  useLegalAdviceStore,
  useLegalSearchStore,
} from "./store";
import { Redirect } from "./components/Redirect";
import { ContractReview } from "./pages/ContractReview";
import { UmpirageGenertation } from "./pages/UmpirageGenertation";
import { Login } from "./pages/Login";
import { SvgIcon } from "./components/SvgIcon";
import { Condition } from "./components/Condition";
import {
  fetchLogout,
  getPhoneNumber,
  getUserId,
} from "./api/server/recommend_question";

type MenuItem = Required<MenuProps>["items"][number];

function App() {
  const clearLegalAdvice = useLegalAdviceStore((state) => state.clear);
  const clearDocGeneration = useDocGenerationStore((state) => state.clear);
  const clearLegalSearch = useLegalSearchStore((state) => state.clear);
  const isYongGongXia = useAppStore((state) => state.isYongGongXia);
  const setLogined = useAppStore((state) => state.setLogined);
  const logined = useAppStore((state) => state.logined);
  const [showAddGroup, setShowAddGroup] = useState(false);
  const nav = useNavigate();
  const loc = useLocation();
  const current = useMemo(() => {
    clearLegalAdvice();
    clearDocGeneration();
    clearLegalSearch();
    return loc.pathname?.split("/")?.[1];
  }, [loc.pathname]);

  const hideMenu = useMemo(() => {
    return (
      loc.pathname?.indexOf("/lawDetail") === 0 ||
      loc.pathname?.indexOf("/caseDetail") === 0
    );
  }, [loc.pathname]);

  console.log(loc);

  const items: MenuItem[] = [
    {
      label: "法律咨询",
      key: "legal-advice",
    },
    {
      label: "文书生成",
      key: "doc-generation",
    },
  ];

  if (!isYongGongXia) {
    items.push(
      ...[
        {
          label: "法律检索",
          key: "legal-search",
        },
        // {
        //   label: "文本阅读",
        //   key: "text-read",
        // },
        {
          label: "合同审查",
          key: "contract-review",
        },
        {
          label: "裁决书生成",
          key: "umpirage-genertation",
        },
      ]
    );
  }

  const onClick: MenuProps["onClick"] = (e) => {
    console.log("click ", e);
    nav({
      pathname: "/" + e.key,
    });
  };

  const onLogout = () => {
    fetchLogout().then((res) => {
      if (res.data.success) {
        setLogined(false);
      } else {
        message.warning(res.data.message);
      }
    });
  };

  return (
    <div className="flex flex-col w-full h-full">
      {!hideMenu && (
        <div className="PageHeader">
          <img src="/images/logo3.png" style={{ width: 120 }} />
          <div className="flex-1 min-w-0 ml-[30px]">
            <Menu
              onClick={onClick}
              selectedKeys={[current]}
              mode="horizontal"
              items={items}
            />
          </div>
          <Condition condition={logined}>
            <Popover
              overlayClassName={"none-padding-popover"}
              placement="bottomRight"
              title={
                <div
                  className="flex flex-col text-[#2c2c36] text-[14px] font-bold p-[20px] rounded-[8px] w-[320px] overflow-hidden text-ellipsis whitespace-nowrap"
                  style={{
                    background:
                      "radial-gradient(67% 180% at 5% -85%,#357ef266 2%,#c4d8ff00)",
                  }}
                >
                  <div>{getPhoneNumber() || getUserId()}</div>
                </div>
              }
              content={
                <div className="flex flex-col">
                  <Divider style={{ margin: 0 }} />
                  <div className="px-[15px] py-[15px]">
                    <div className="text-[#2c2c36] text-[14px] font-bold">
                      用户权益
                    </div>
                    <Progress
                      percent={60}
                      strokeColor={{
                        "0%": "#5493f4",
                        "50%": "#ADC9FF",
                        "100%": "#ADC9FF",
                      }}
                    />
                    <div className="flex flex-row items-center justify-between text-[12px] text-[#2c2c36] mt-[8px]">
                      <div>合同审查</div>
                      <div className="flex flex-row items-center text-[#8f91a8]">
                        <span>剩余</span>
                        <span className="text-[#2c2c36]">2</span>
                        <span>份</span>
                        <span>/</span>
                        <span>共</span>
                        <span className="text-[#2c2c36]">3</span>
                        <span>份</span>
                      </div>
                    </div>
                  </div>
                  <Divider style={{ margin: 0 }} />
                  <div className="flex flex-col m-[4px]">
                    <div
                      className="flex flex-row items-center cursor-pointer hover:bg-[#f2f7ff] px-[14px] py-[6px] gap-[8px]"
                      onClick={() => {
                        setShowAddGroup(true);
                      }}
                    >
                      <SvgIcon name="tongyi-userGroup-line" />
                      <span>交流群</span>
                    </div>
                  </div>
                  <Divider style={{ margin: 0 }} />
                  <div className="flex flex-col m-[4px]">
                    <div
                      className="flex flex-row items-center cursor-pointer hover:bg-[#f2f7ff] px-[14px] py-[6px] gap-[8px] text-[#eb2f2f]"
                      onClick={onLogout}
                    >
                      <SvgIcon name="tongyi-escape-line" />
                      <span>退出登录</span>
                    </div>
                  </div>
                </div>
              }
              arrow={false}
              trigger={["click"]}
            >
              <div className="flex flex-row items-center gap-[8px] hover:bg-[#f2f7ff] p-[6px] rounded-[16px] cursor-pointer">
                <img src="/images/user.png" className="w-[24px]" />
                <SvgIcon name="tongyi-down-line" />
              </div>
            </Popover>
          </Condition>
        </div>
      )}
      <div className="flex flex-col flex-1 min-h-0">
        <div className="flex-1 min-h-0">
          <Routes>
            <Route path="/legal-advice" element={<LegalAdvice />} />
            <Route path="/doc-generation" element={<DocGeneration />} />
            {!isYongGongXia && (
              <Route path="/legal-search" element={<LegalSearch />} />
            )}
            {!isYongGongXia && (
              <Route path="/text-read" element={<TextRead />} />
            )}
            {!isYongGongXia && (
              <Route
                path="/contract-review"
                element={
                  <ContractReview>
                    <div className="w-full h-full flex flex-row items-center justify-center">
                      敬请期待
                    </div>
                  </ContractReview>
                }
              />
            )}
            {!isYongGongXia && (
              <Route
                path="/umpirage-genertation"
                element={
                  <UmpirageGenertation>
                    <div className="w-full h-full flex flex-row items-center justify-center">
                      敬请期待
                    </div>
                  </UmpirageGenertation>
                }
              />
            )}
            <Route path="/caseDetail/:id" element={<CaseDetail />} />
            <Route path="/lawDetail/:id" element={<LawDetail />} />
            <Route path="*" element={<Redirect to="/legal-advice" />} />
          </Routes>
          {!logined && <Login />}
        </div>

        <div className="text-[12px] text-[#9d9cac] text-center">
          <div className="flex flex-col gap-2 py-2">
            <div className="flex flex-row items-center justify-center gap-2">
              <div className="flex flex-row items-center">
                <img src="/images/foot-img-mini.png" className="h-[22px]" />
              </div>

              <div className="flex flex-row gap-2">
                <a
                  target="_blank"
                  href="https://beian.miit.gov.cn"
                  rel="noreferrer"
                >
                  <span>京ICP备19049955号-6</span>
                </a>
              </div>
            </div>
          </div>
        </div>
      </div>
      <Modal
        open={showAddGroup}
        onCancel={() => setShowAddGroup(false)}
        footer={null}
        wrapClassName="none-padding-modal"
      >
        <div
          style={{
            backgroundImage: "url(/images/border.jpg)",
            backgroundSize: "100% 100%",
          }}
          className="rounded-[8px] p-[8px]"
        >
          <div className="bg-white rounded-[8px] flex flex-col p-[32px]">
            <div className="text-[#2c2c36] text-[18px] font-bold">用户交流</div>
            <div className="text-[#585a73] text-[14px] pt-[8px]">
              反馈问题、提供建议，让白话用工侠更好用。
            </div>
            <Divider />
            <div className="flex flex-col items-center gap-[8px] pb-[24px]">
              <img src="/images/image.png" className="w-[242px]" />
              <div className="text-[#2c2c36] text-[16px] font-bold pt-[20px]">
                加入 <span className="text-[#185fee]">白话用工侠</span>{" "}
                用户交流群
              </div>
              <div className="text-[12px]">使用微信扫描上方二维码</div>
            </div>
          </div>
        </div>
      </Modal>
    </div>
  );
}

export default App;
